package com.vrv.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.TabActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.app.main.LawsActivity;
import com.vrv.app.main.NoticeActivity;
import com.vrv.app.main.QueryActivity;
import com.vrv.app.main.TaskActivity;
import com.vrv.common.Constants;
import com.vrv.common.utils.ViewUtils;
import com.vrv.common.widget.SimpleSlideMenu;
import com.vrv.common.widget.SimpleSlideMenu.OnScrollListener;

@SuppressWarnings("deprecation")
public class MainTableActivity extends TabActivity implements OnTouchListener, GestureDetector.OnGestureListener {

    /** PUPWin相关 */
    private FrameLayout footLayout;
    private FrameLayout btnContainer;
    private PopupWindow popupWin;

    /** SliderMenu相关 */

    /** 是否Measured */
    private boolean hasMeasured = false;
    /** 左边布局 */
    private LinearLayout layout_left;
    /* 右边布局 */
    private LinearLayout layout_right;
    /* Setting图片 */
    private ImageView settingBtn;//
    private ListView lv_set;// 设置菜单
    /** 每次自动展开/收缩的范围 */
    private int MAX_WIDTH = 0;
    private final static int SPEED = 30;
    private final static int sleep_time = 5;
    private GestureDetector mGestureDetector;// 手势
    private boolean isScrolling = false;
    private float mScrollX; // 滑块滑动距离
    private int window_width;// 屏幕的宽度
    private View view = null;// 点击的view
    private String title[] = { "个人资料", "关于", "帮助", "版本更新", "数据推送", "数据同步", "注销登录" };
    private String action[] = { "com.vrv.app.account.MyAccountActivity", "com.vrv.app.AboutActivity", "", "", "logout" };
    private SimpleSlideMenu mylaout;

    private TextView textView1;
    private TextView textView2;
    private TextView textView3;
    private TextView textView4;

    private TabHost tabHost;
    private LinearLayout linearLayout1;
    private LinearLayout linearLayout2;
    private LinearLayout linearLayout3;
    private LinearLayout linearLayout4;

    public static final String TAB_TASK = "tabTask";
    public static final String TAB_NOTICE = "tabNotice";
    public static final String TAB_QUERY = "tabQuery";
    public static final String TAB_LAWS = "tabLaws";

    private TextView titleTxt;
    @SuppressWarnings("unused")
    private ImageButton backBtn;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        initView();
        getMAX_WIDTH();

        initLocalData();
    }

    /**
     * 初始化本地数据库
     */
    private void initLocalData() {
        // TODO Auto-generated method stub
        AssetManager assetManager = getAssets();
        InputStream inputStream = null;
        FileOutputStream outputStream = null;

        try {
            // String path =
            // getApplicationContext().getFilesDir().getAbsolutePath()+
            // "/databases/ples.db";
            File dir = new File("data/data/" + getPackageName() + "/databases");
            if (!dir.exists() || !dir.isDirectory()) {
                dir.mkdir();
            }
            File file = new File(dir, "ples.db");
            inputStream = assetManager.open("ples.db");
            outputStream = new FileOutputStream(file);// openFileOutput("ples.db",
                                                      // Context.MODE_PRIVATE);//
            byte[] buffer = new byte[1024];
            int currentReadLength = inputStream.read(buffer);
            while (currentReadLength != -1) {
                outputStream.write(buffer, 0, currentReadLength);
                currentReadLength = inputStream.read(buffer);
                if (currentReadLength == -1) {
                    outputStream.flush();
                }
            }
            // assetManager.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }

    /**
     * 初始化视图组件
     */
    private void initView() {
        titleTxt = (TextView) findViewById(R.id.title_text);
        setTitle(getResources().getString(R.string.taskInfo));

        footLayout = (FrameLayout) findViewById(R.id.footLayout);
        btnContainer = (FrameLayout) findViewById(R.id.btn_container);

        layout_left = (LinearLayout) findViewById(R.id.layout_left);
        layout_right = (LinearLayout) findViewById(R.id.layout_right);
        settingBtn = (ImageView) findViewById(R.id.iv_set);
        lv_set = (ListView) findViewById(R.id.lv_set);
        mylaout = (SimpleSlideMenu) findViewById(R.id.mylaout);

        layout_right.setOnTouchListener(this);
        layout_left.setOnTouchListener(this);
        settingBtn.setOnTouchListener(this);
        mGestureDetector = new GestureDetector(this);
        mGestureDetector.setIsLongpressEnabled(false);// 禁用长按监听
        getMAX_WIDTH();

        tabHost = getTabHost();
        tabHost.addTab(tabHost.newTabSpec(TAB_TASK).setIndicator(TAB_TASK).setContent(new Intent(this, TaskActivity.class)));
        tabHost.addTab(tabHost.newTabSpec(TAB_QUERY).setIndicator(TAB_QUERY).setContent(new Intent(this, QueryActivity.class)));
        tabHost.addTab(tabHost.newTabSpec(TAB_NOTICE).setIndicator(TAB_NOTICE).setContent(new Intent(this, NoticeActivity.class)));
        tabHost.addTab(tabHost.newTabSpec(TAB_LAWS).setIndicator(TAB_LAWS).setContent(new Intent(this, LawsActivity.class)));
        tabHost.setCurrentTabByTag(TAB_TASK);

        //
        textView1 = (TextView) this.findViewById(R.id.main_tv1);
        textView2 = (TextView) this.findViewById(R.id.main_tv2);
        textView3 = (TextView) this.findViewById(R.id.main_tv3);
        textView4 = (TextView) this.findViewById(R.id.main_tv4);

        linearLayout1 = (LinearLayout) this.findViewById(R.id.main_layout1);
        linearLayout2 = (LinearLayout) this.findViewById(R.id.main_layout2);
        linearLayout3 = (LinearLayout) this.findViewById(R.id.main_layout3);
        linearLayout4 = (LinearLayout) this.findViewById(R.id.main_layout4);
        //
        linearLayout1.setOnClickListener(labelClickListener);
        linearLayout2.setOnClickListener(labelClickListener);
        linearLayout3.setOnClickListener(labelClickListener);
        linearLayout4.setOnClickListener(labelClickListener);

        btnContainer.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (popupWin != null && popupWin.isShowing()) {
                    popupWin.dismiss();
                } else {
                    showWindow(footLayout);
                }
            }
        });

        lv_set.setAdapter(new ArrayAdapter<String>(this, R.layout.item, R.id.tv_item, title));
        mylaout.setOnScrollListener(new OnScrollListener() {
            @Override
            public void doScroll(float distanceX) {
                doScrolling(distanceX);
            }

            @Override
            public void doLoosen() {
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_left.getLayoutParams();
                Log.e(Constants.TAG, "layoutParams.leftMargin=" + layoutParams.leftMargin);
                if (layoutParams.leftMargin < -window_width / 2) {// 缩回去
                    new AsynMove().execute(-SPEED);
                } else {
                    new AsynMove().execute(SPEED);
                }
            }
        });

        lv_set.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_left.getLayoutParams();
                // 只要没有滑动则都属于点击
                if (layoutParams.leftMargin == -MAX_WIDTH) {
                    String actionuri = action[position];
                    if ("logout".equals(actionuri)) {
                        ViewUtils.quit(MainTableActivity.this);
                    } else if (!"".equals(actionuri)) {
                        ComponentName componentName = new ComponentName(MainTableActivity.this, actionuri);
                        Intent intent = new Intent();
                        intent.setComponent(componentName);
                        overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
                        startActivity(intent);
                    } else {
                        Toast.makeText(MainTableActivity.this, title[position], Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    /**
     * 显示PUPWindow
     *
     * @param parent
     */
    private void showWindow(View parent) {
        if (popupWin == null) {
            View view = LayoutInflater.from(MainTableActivity.this).inflate(R.layout.float_layer, null);
            popupWin = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, 320);
        }
        popupWin.setFocusable(true);
        popupWin.setOutsideTouchable(true);// 设置允许在外点击消失
        popupWin.setBackgroundDrawable(new BitmapDrawable());// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWin.setTouchInterceptor(new OnTouchListener() {
            public boolean onTouch(View view, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    popupWin.dismiss();
                    return true;
                }
                return false;
            }
        });
        popupWin.showAsDropDown(parent, Gravity.CENTER, 0);
    }

    /**
     * 设置TextView的背景
     *
     * @param id
     */
    private void setLinearLayoutBackground(int id) {

        List<LinearLayout> linearLayoutList = new ArrayList<LinearLayout>();
        linearLayoutList.add(linearLayout1);
        linearLayoutList.add(linearLayout2);
        linearLayoutList.add(linearLayout3);
        linearLayoutList.add(linearLayout4);
        for (LinearLayout linearLayout : linearLayoutList) {
            if (linearLayout.getId() == id) {
                linearLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_selected));
                switch (linearLayout.getId()) {
                case R.id.main_layout1:
                    textView1.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_task_select, 0, 0);
                    textView2.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_query, 0, 0);
                    textView3.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_notice, 0, 0);
                    textView4.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_laws, 0, 0);
                    break;
                case R.id.main_layout2:
                    textView2.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_query_select, 0, 0);
                    textView1.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_task, 0, 0);
                    textView3.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_notice, 0, 0);
                    textView4.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_laws, 0, 0);
                    break;
                case R.id.main_layout3:
                    textView3.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_notice_select, 0, 0);
                    textView1.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_task, 0, 0);
                    textView2.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_query, 0, 0);
                    textView4.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_laws, 0, 0);
                    break;
                case R.id.main_layout4:
                    textView4.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_laws_select, 0, 0);
                    textView1.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_task, 0, 0);
                    textView2.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_query, 0, 0);
                    textView3.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.png_notice, 0, 0);
                    break;
                }
            } else {
                linearLayout.setBackgroundDrawable(null);
            }
        }
    }

    /**
     * 设置标题
     */
    public void setTitle(String title) {
        titleTxt.setText(title);
    }

    /**
     * 点击Tab事件
     */
    OnClickListener labelClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            String curTabTag = tabHost.getCurrentTabTag();
            setLinearLayoutBackground(v.getId());
            switch (v.getId()) {
            case R.id.main_layout1:
                if (!curTabTag.equals(TAB_TASK)) {
                    tabHost.setCurrentTabByTag(TAB_TASK);
                    setTitle(MainTableActivity.this.getString(R.string.taskInfo));
                }
                break;
            case R.id.main_layout2:
                if (!curTabTag.equals(TAB_QUERY)) {
                    tabHost.setCurrentTabByTag(TAB_QUERY);
                    setTitle(MainTableActivity.this.getString(R.string.queryInfo));
                }
                break;
            case R.id.main_layout3:
                if (!curTabTag.equals(TAB_NOTICE)) {
                    tabHost.setCurrentTabByTag(TAB_NOTICE);
                    setTitle(MainTableActivity.this.getString(R.string.notice));
                }
                break;
            case R.id.main_layout4:
                if (!curTabTag.equals(TAB_LAWS)) {
                    tabHost.setCurrentTabByTag(TAB_LAWS);
                    setTitle(MainTableActivity.this.getString(R.string.lawInfo));
                }
                break;
            }

        }
    };

    // [start] GestureDetector 相关方法
    /***
     * listview 正在滑动时执行.
     */
    void doScrolling(float distanceX) {
        isScrolling = true;
        mScrollX += distanceX;// distanceX:向左为正，右为负

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_left.getLayoutParams();
        RelativeLayout.LayoutParams layoutParams_1 = (RelativeLayout.LayoutParams) layout_right.getLayoutParams();
        layoutParams.leftMargin -= mScrollX;
        layoutParams_1.leftMargin = window_width + layoutParams.leftMargin;
        if (layoutParams.leftMargin >= 0) {
            isScrolling = false;// 拖过头了不需要再执行AsynMove了
            layoutParams.leftMargin = 0;
            layoutParams_1.leftMargin = window_width;

        } else if (layoutParams.leftMargin <= -MAX_WIDTH) {
            // 拖过头了不需要再执行AsynMove了
            isScrolling = false;
            layoutParams.leftMargin = -MAX_WIDTH;
            layoutParams_1.leftMargin = window_width - MAX_WIDTH;
        }
        Log.v(Constants.TAG, "layoutParams.leftMargin=" + layoutParams.leftMargin + ",layoutParams_1.leftMargin =" + layoutParams_1.leftMargin);

        layout_left.setLayoutParams(layoutParams);
        layout_right.setLayoutParams(layoutParams_1);
    }

    /***
     * 获取移动距离 移动的距离其实就是layout_left的宽度
     */
    void getMAX_WIDTH() {
        ViewTreeObserver viewTreeObserver = layout_left.getViewTreeObserver();
        // 获取控件宽度
        viewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!hasMeasured) {
                    window_width = getWindowManager().getDefaultDisplay().getWidth();
                    MAX_WIDTH = layout_right.getWidth();
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_left.getLayoutParams();
                    RelativeLayout.LayoutParams layoutParams_1 = (RelativeLayout.LayoutParams) layout_right.getLayoutParams();
                    ViewGroup.LayoutParams layoutParams_2 = mylaout.getLayoutParams();
                    // 注意： 设置layout_left的宽度。防止被在移动的时候控件被挤压
                    layoutParams.width = window_width;
                    layout_left.setLayoutParams(layoutParams);

                    // 设置layout_right的初始位置.
                    layoutParams_1.leftMargin = window_width;
                    layout_right.setLayoutParams(layoutParams_1);
                    // 注意：设置lv_set的宽度防止被在移动的时候控件被挤压
                    layoutParams_2.width = MAX_WIDTH;
                    mylaout.setLayoutParams(layoutParams_2);

                    Log.v(Constants.TAG, "MAX_WIDTH=" + MAX_WIDTH + "width=" + window_width);
                    hasMeasured = true;
                }
                return true;
            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_left.getLayoutParams();
            if (layoutParams.leftMargin < 0) {
                new AsynMove().execute(SPEED);
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        view = v;// 记录点击的控件

        // 松开的时候要判断，如果不到半屏幕位子则缩回去，
        if (MotionEvent.ACTION_UP == event.getAction() && isScrolling == true) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_left.getLayoutParams();
            // 缩回去
            if (layoutParams.leftMargin < -window_width / 2) {
                new AsynMove().execute(-SPEED);
            } else {
                new AsynMove().execute(SPEED);
            }
        }

        return mGestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent e) {

        int position = lv_set.pointToPosition((int) e.getX(), (int) e.getY());
        if (position != ListView.INVALID_POSITION) {
            View child = lv_set.getChildAt(position - lv_set.getFirstVisiblePosition());
            if (child != null)
                child.setPressed(true);
        }

        mScrollX = 0;
        isScrolling = false;
        // 将之改为true，才会传递给onSingleTapUp,不然事件不会向下传递.
        return true;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    /***
     * 点击松开执行
     */
    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        // 点击的不是layout_left
        if (view != null && view == settingBtn) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_left.getLayoutParams();
            // 左移动
            if (layoutParams.leftMargin >= 0) {
                new AsynMove().execute(-SPEED);
                lv_set.setSelection(0);// 设置为首位.
            } else {
                // 右移动
                new AsynMove().execute(SPEED);
            }
        } else if (view != null && view == layout_left) {
            RelativeLayout.LayoutParams layoutParams = (android.widget.RelativeLayout.LayoutParams) layout_left.getLayoutParams();
            if (layoutParams.leftMargin < 0) {
                // 说明layout_left处于移动最左端状态，这个时候如果点击layout_left应该直接所以原有状态.(更人性化)
                // 右移动
                new AsynMove().execute(SPEED);
            }
        }

        return true;
    }

    /***
     * 滑动监听 就是一个点移动到另外一个点. distanceX=后面点x-前面点x，如果大于0，说明后面点在前面点的右边及向右滑动
     */
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        // 执行滑动.
        doScrolling(distanceX);
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    class AsynMove extends AsyncTask<Integer, Integer, Void> {

        @Override
        protected Void doInBackground(Integer... params) {
            int times = 0;
            if (MAX_WIDTH % Math.abs(params[0]) == 0) {// 整除
                times = MAX_WIDTH / Math.abs(params[0]);
            } else {
                times = MAX_WIDTH / Math.abs(params[0]) + 1;// 有余数
            }

            for (int i = 0; i < times; i++) {
                publishProgress(params[0]);
                try {
                    Thread.sleep(sleep_time);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_left.getLayoutParams();
            RelativeLayout.LayoutParams layoutParams_1 = (RelativeLayout.LayoutParams) layout_right.getLayoutParams();
            if (values[0] > 0) { // 右移动
                layoutParams.leftMargin = Math.min(layoutParams.leftMargin + values[0], 0);
                layoutParams_1.leftMargin = Math.min(layoutParams_1.leftMargin + values[0], window_width);
                Log.v(Constants.TAG, "layout_left右" + layoutParams.leftMargin + ",layout_right右" + layoutParams_1.leftMargin);
            } else {// 左移动
                layoutParams.leftMargin = Math.max(layoutParams.leftMargin + values[0], -MAX_WIDTH);
                layoutParams_1.leftMargin = Math.max(layoutParams_1.leftMargin + values[0], window_width - MAX_WIDTH);
                Log.v(Constants.TAG, "layout_left左" + layoutParams.leftMargin + ",layout_right左" + layoutParams_1.leftMargin);
            }
            layout_right.setLayoutParams(layoutParams_1);
            layout_left.setLayoutParams(layoutParams);
        }
    }
    // [end] GestureDetector 相关方法
}
